<template>
  <div class="user-profile">
    <el-row :gutter="20">
      <!-- 个人资料 -->
      <el-col :span="14">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人资料</span>
            </div>
          </template>

          <el-form
              :model="userInfo"
              label-width="100px"
              class="profile-form"
          >
            <el-form-item label="用户名">
              <el-input v-model="userInfo.username" disabled />
            </el-form-item>

            <el-form-item label="邮箱">
              <el-input v-model="userInfo.email" disabled />
            </el-form-item>

            <el-form-item label="手机号">
              <el-input v-model="userInfo.phone" disabled />
            </el-form-item>

            <el-form-item label="注册时间">
              <el-input v-model="userInfo.register_time" disabled />
            </el-form-item>

            <el-form-item label="头像">
              <div v-if="userInfo.avatar" class="avatar-container">
                <img :src="userInfo.avatar" alt="头像" class="avatar" />
              </div>
              <div v-else class="no-avatar">
                无头像
              </div>
              <!-- 添加上传按钮 -->
              <div style="margin-top: 15px;">
                <el-upload
                    class="avatar-uploader"
                    action="/api/user/upload/file"
                    :show-file-list="false"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                >
                  <el-button type="primary">上传头像</el-button>
                </el-upload>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 收货地址 -->
      <el-col :span="10">
        <el-card class="address-card">
          <template #header>
            <div class="card-header">
              <span>收货地址</span>
              <el-button type="primary" size="small" @click="showAddAddressDialog" style="float: right;">
                新增收货地址
              </el-button>
            </div>
          </template>

          <div v-if="loadingAddresses" class="loading">
            加载中...
          </div>

          <div v-else>
            <div v-if="userAddresses.length === 0" class="empty-address">
              暂无收货地址
            </div>

            <div v-else>
              <div
                  v-for="address in userAddresses"
                  :key="address.id"
                  class="address-item"
                  :class="{ 'selected': selectedAddressId === address.id }"
                  @click="selectAddress(address.id)"
              >
                <div class="address-header">
                  <span class="receiver">{{ address.receiver_name }}</span>
                  <span class="phone">{{ address.receiver_phone }}</span>
                  <div class="address-actions">
                    <el-tag v-if="address.is_default === 1" type="success" size="small" style="margin-right: 5px;">默认</el-tag>
                    <el-button v-if="address.is_default !== 1" type="primary" link @click.stop="setDefaultAddress(address.id)">
                      设为默认
                    </el-button>
                    <el-button type="primary" link @click.stop="showEditAddressDialog(address)">
                      编辑
                    </el-button>
                    <el-button type="danger" link @click.stop="deleteAddress(address.id)">
                      删除
                    </el-button>
                  </div>
                </div>
                <div class="address-detail">
                  {{ formatFullAddress(address) }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增收货地址对话框 -->
    <el-dialog
        v-model="addAddressDialogVisible"
        :title="editingAddress ? '编辑收货地址' : '新增收货地址'"
        width="500px"
    >
      <el-form
          :model="addressForm"
          ref="addressFormRef"
          label-width="100px"
          :rules="addressFormRules"
      >
        <el-form-item label="收货人" prop="receiver_name">
          <el-input v-model="addressForm.receiver_name" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="receiver_phone">
          <el-input v-model="addressForm.receiver_phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="省份" prop="province">
          <el-input v-model="addressForm.province" placeholder="请输入省份"></el-input>
        </el-form-item>

        <el-form-item label="城市" prop="city">
          <el-input v-model="addressForm.city" placeholder="请输入城市"></el-input>
        </el-form-item>

        <el-form-item label="区/县" prop="district">
          <el-input v-model="addressForm.district" placeholder="请输入区/县"></el-input>
        </el-form-item>

        <el-form-item label="详细地址" prop="detail_addr">
          <el-input
              v-model="addressForm.detail_addr"
              placeholder="请输入详细地址"
              type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAddressDialog">取消</el-button>
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import userApi from '../../api/user_api.js'
import loginApi from "@/api/login_api.js"
import deliveryAddrApi from '@/api/deliveryAddr_api.js'

//转换时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  return dateTimeStr.replace('T', ' ');
}

const userInfo = ref({
  id: 1,
  username: '',
  email: '',
  phone: '',
  register_time: '',
  avatar: ''
})

const loginAdmin = ref({});

// 地址相关数据
const userAddresses = ref([])
const selectedAddressId = ref('')
const addAddressDialogVisible = ref(false)
const addressFormRef = ref(null)
const editingAddress = ref(null)
const loadingAddresses = ref(false)

// 地址表单
const addressForm = reactive({
  id: '',
  receiver_name: '',
  receiver_phone: '',
  province: '',
  city: '',
  district: '',
  detail_addr: '',
  user_id: ''
})

// 地址表单验证规则
const addressFormRules = {
  receiver_name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  receiver_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  district: [
    { required: true, message: '请输入区/县', trigger: 'blur' }
  ],
  detail_addr: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 获取用户信息
const getUserInfo = async () => {
  try {
    // 通过 token 获取当前登录用户 ID
    loginAdmin.value = await loginApi.logininfo();
    console.log("登录用户信息:", loginAdmin.value);

    // 获取当前登录的用户详细信息
    const detailedInfo = await userApi.getUserById(loginAdmin.value.id);
    console.log("详细用户信息:", detailedInfo);

    // 正确合并信息
    userInfo.value = {
      ...userInfo.value,
      ...detailedInfo,
      register_time: formatDateTime(detailedInfo.create_time || detailedInfo.register_time || '')
    };

    // 特别处理头像字段
    if (detailedInfo.avatar) {
      userInfo.value.avatar = detailedInfo.avatar;
    }

    // 获取用户地址
    await fetchUserAddresses();
  } catch (error) {
    ElMessage.error('获取用户信息失败: ' + (error.message || '未知错误'));
  }
}

// 获取用户地址列表
const fetchUserAddresses = async () => {
  if (!loginAdmin.value || !loginAdmin.value.id) return;

  loadingAddresses.value = true;
  try {
    const res = await deliveryAddrApi.getAddrsByUserId(loginAdmin.value.id);
    if (res && Array.isArray(res)) {
      userAddresses.value = res;
      // 如果有地址，默认选择第一个
      if (userAddresses.value.length > 0 && !selectedAddressId.value) {
        selectedAddressId.value = userAddresses.value[0].id;
      }
    }
  } catch (err) {
    console.error('获取用户地址失败:', err);
    ElMessage.error('获取地址信息失败');
  } finally {
    loadingAddresses.value = false;
  }
}

// 格式化完整地址
const formatFullAddress = (addr) => {
  return `${addr.province}${addr.city}${addr.district}${addr.detail_addr}`;
}

// 选择地址
const selectAddress = (id) => {
  selectedAddressId.value = id;
}

// 设置默认地址
const setDefaultAddress = async (id) => {
  try {
    // 先将所有地址设为非默认
    for (const addr of userAddresses.value) {
      if (addr.is_default === 1) {
        await deliveryAddrApi.updateAddr({
          id: addr.id,
          is_default: 0
        });
      }
    }

    // 再将选中地址设为默认
    const res = await deliveryAddrApi.updateAddr({
      id: id,
      is_default: 1
    });

    if (res) {
      ElMessage.success('默认地址设置成功');
      // 重新获取地址列表
      await fetchUserAddresses();
    } else {
      ElMessage.error('默认地址设置失败');
    }
  } catch (err) {
    console.error('设置默认地址失败:', err);
    ElMessage.error('默认地址设置失败');
  }
}

// 显示新增地址对话框
const showAddAddressDialog = () => {
  editingAddress.value = null;
  // 重置表单
  Object.assign(addressForm, {
    id: '',
    receiver_name: '',
    receiver_phone: '',
    province: '',
    city: '',
    district: '',
    detail_addr: '',
    user_id: loginAdmin.value.id
  });
  addAddressDialogVisible.value = true;
}

// 显示编辑地址对话框
const showEditAddressDialog = (address) => {
  editingAddress.value = address;
  // 填充表单
  Object.assign(addressForm, {
    id: address.id,
    receiver_name: address.receiver_name,
    receiver_phone: address.receiver_phone,
    province: address.province,
    city: address.city,
    district: address.district,
    detail_addr: address.detail_addr,
    user_id: loginAdmin.value.id
  });
  addAddressDialogVisible.value = true;
}

// 取消地址对话框
const cancelAddressDialog = () => {
  addAddressDialogVisible.value = false;
  editingAddress.value = null;
}

// 保存地址
const saveAddress = async () => {
  addressFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res;
        // 检查用户是否已有地址，如果没有，则将新地址设为默认地址
        if (userAddresses.value.length === 0) {
          addressForm.is_default = 1;
        } else {
          addressForm.is_default = 0;
        }

        if (editingAddress.value) {
          // 编辑地址
          res = await deliveryAddrApi.updateAddr(addressForm);
        } else {
          // 新增地址
          res = await deliveryAddrApi.addAddr(addressForm);
        }

        if (res) {
          ElMessage.success(editingAddress.value ? '地址更新成功' : '地址添加成功');
          addAddressDialogVisible.value = false;
          editingAddress.value = null;
          // 重新获取地址列表
          await fetchUserAddresses();
        } else {
          ElMessage.error(res?.message || (editingAddress.value ? '地址更新失败' : '地址添加失败'));
        }
      } catch (err) {
        console.error('保存地址失败:', err);
        ElMessage.error(editingAddress.value ? '地址更新失败' : '地址添加失败');
      }
    }
  });
}

// 删除地址
const deleteAddress = (id) => {
  ElMessageBox.confirm(
      '确认删除该收货地址吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const res = await deliveryAddrApi.deleteAddr(id);
      if (res) {
        ElMessage.success('地址删除成功');
        // 重新获取地址列表
        await fetchUserAddresses();
        // 如果删除的是选中的地址，清空选中
        if (selectedAddressId.value === id) {
          selectedAddressId.value = userAddresses.value.length > 0 ? userAddresses.value[0].id : '';
        }
      } else {
        ElMessage.error('地址删除失败');
      }
    } catch (err) {
      console.error('删除地址失败:', err);
      ElMessage.error('地址删除失败');
    }
  }).catch(() => {
    // 用户取消删除
  });
}

// 处理用户信息更新事件
const handleUserInfoUpdated = () => {
  getUserInfo();
}

// 处理上传成功
const handleUploadSuccess = async (response, file) => {
  try {
    // 从响应中获取图片URL
    const avatarUrl = response.data || response; // 根据实际API响应结构调整

    // 更新用户头像
    const updateData = {
      id: loginAdmin.value.id,
      avatar: avatarUrl
    };

    await userApi.updateUser(updateData);

    // 更新本地显示
    userInfo.value.avatar = avatarUrl;

    // 发送全局事件通知其他组件刷新数据
    window.dispatchEvent(new CustomEvent('user-info-updated'));

    ElMessage.success('头像上传成功');
  } catch (error) {
    ElMessage.error('头像更新失败: ' + (error.message || '未知错误'));
  }
}

// 处理上传失败
const handleUploadError = (error) => {
  ElMessage.error('头像上传失败: ' + (error.message || '未知错误'));
}

onMounted(() => {
  getUserInfo();

  // 监听用户信息更新事件
  window.addEventListener('user-info-updated', handleUserInfoUpdated);
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('user-info-updated', handleUserInfoUpdated);
})
</script>

<style scoped>
/* 淘宝风格的用户资料页面 */
.user-profile {
  padding: 20px;
  margin: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 个人资料卡片样式 */
.profile-card {
  background-color: #ffffff !important;
  border: none !important;
  border-radius: 4px !important;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1) !important;
  height: 100%;
}

/* 地址卡片样式 */
.address-card {
  background-color: #ffffff !important;
  border: none !important;
  border-radius: 4px !important;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1) !important;
  height: 100%;
}

/* 卡片标题样式 */
.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #333333;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  background-color: #ffffff;
}

/* 表单样式调整 */
.profile-form {
  padding: 30px 24px;
  background-color: #ffffff;
}

/* 表单项整体样式 */
.profile-form :deep(.el-form-item) {
  margin-bottom: 22px;
  display: flex;
}

/* 表单项标签样式 */
.profile-form :deep(.el-form-item__label) {
  color: #666666;
  font-size: 14px;
  padding-right: 15px;
  text-align: right;
  line-height: 38px;
  width: 100px !important;
}

/* 输入框容器样式 */
.profile-form :deep(.el-form-item__content) {
  flex: 1;
  line-height: 38px;
}

/* 输入框样式 */
.profile-form :deep(.el-input__inner) {
  background-color: #ffffff !important;
  border: 1px solid #dcdfe6 !important;
  color: #333333 !important;
  height: 38px;
  border-radius: 4px;
  padding: 0 12px;
  font-size: 14px;
}

.profile-form :deep(.el-input__inner):focus {
  border-color: #ff4400 !important;
  outline: 0;
  box-shadow: 0 0 0 2px rgba(255, 68, 0, 0.2);
}

/* 输入框禁用状态样式 */
.profile-form :deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa !important;
  color: #999999 !important;
  cursor: not-allowed;
  border-color: #e4e7ed !important;
}

/* 头像容器样式 */
.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: #f5f5f5;
  overflow: hidden;
  border: 1px solid #e0e0e0;
}

/* 头像图片样式 */
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.avatar:hover {
  transform: scale(1.05);
}

/* 无头像提示样式 */
.no-avatar {
  text-align: center;
  color: #999999;
  font-size: 14px;
  padding: 40px 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
}

/* 上传按钮样式 */
.avatar-uploader :deep(.el-upload) {
  display: block;
}

.avatar-uploader :deep(.el-button) {
  background-color: #ff6b00 !important;
  border-color: #ff6b00 !important;
  color: white !important;
  transition: all 0.2s !important;
}

.avatar-uploader :deep(.el-button:hover) {
  background-color: #e55a00 !important;
  border-color: #e55a00 !important;
}

/* 地址相关样式 */
.loading {
  text-align: center;
  padding: 20px;
  color: #999;
}

.empty-address {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.address-item {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #ff6b00;
  box-shadow: 0 2px 6px rgba(255, 107, 0, 0.2);
}

.address-item.selected {
  border-color: #ff6b00;
  background-color: #fff9f2;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.receiver {
  font-weight: bold;
  font-size: 16px;
}

.phone {
  color: #666;
  margin-left: 10px;
}

.address-actions {
  flex-shrink: 0;
}

.address-detail {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}
</style>
